package com.jcli._定时提醒;

import com.jcli.jb51_net.article._232524碰撞小球.Windows;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 在界面文本添加显示剩余时间
 * 右下角也能提示了。
 * 用户能自定义输入时间了，小数也可以，
 * 点击开始后等待计时结束或点击停止后才能再次开始,
 * 关闭界面隐藏到托盘，
 * 托盘左键打开界面，右键菜单栏，
 * 7.右键点击托盘，显示了菜单栏时，没有选择菜单而点击其他位置则隐藏,暂未实现，
 * @author li
 */
public class FocusAssistantApp05 {
    private static final int ONE_SECOND = 1000; // 1秒的毫秒数

    private static Timer timer;
    private static long remainingTime = 0; // 初始剩余时间为0
    private static boolean trayIconCreated = false;

    private static TrayIcon trayIcon; // 定义TrayIcon

    private static JFrame frame; // 声明为全局变量，以便在其他方法中访问

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("swing.boldMetal", Boolean.FALSE); // 额外设置，可选

            SwingUtilities.invokeLater(() -> createAndShowGUI());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
    }

    private static void createAndShowGUI() {
        //Java Swing 非常漂亮外观Nimbus的使用方法实例
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        frame = new JFrame("专注助手");
        // 不执行默认的关闭操作
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        // 添加窗口关闭事件监听器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                minimizeToTray();
            }
        });

        JPanel panel = new JPanel();
        JButton startButton = new JButton("开始专注计时器");
        JButton stopButton = new JButton("停止专注计时器");

        JTextField timeField = new JTextField(5);
        timeField.setText("20");
        JLabel timeLabel = new JLabel("剩余时间: 0 分 0 秒");

        startButton.addActionListener(e -> startFocusTimer(timeLabel, timeField, startButton, stopButton));
        stopButton.addActionListener(e -> stopFocusTimer(startButton, stopButton));

        panel.add(new JLabel("设定时间（分钟）: "));
        panel.add(timeField);
        panel.add(startButton);
        panel.add(stopButton);
        panel.add(timeLabel);

        frame.getContentPane().add(panel, BorderLayout.CENTER);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // 在程序启动时就创建托盘图标
        createTrayIcon();
    }

    private static void minimizeToTray() {
        // frame.setVisible(false); // 隐藏窗口，会提示异常，直接关闭
        frame.dispose();
    }

    private static void startFocusTimer(JLabel timeLabel, JTextField timeField, JButton startButton, JButton stopButton) {
        if (timer != null && timer.isRunning()) {
            timer.stop();
        }

        // 获取用户输入的时间，将其转换为毫秒
        double userInputTime = Double.parseDouble(timeField.getText()) * 60 * ONE_SECOND;
        remainingTime = (long) userInputTime;


        timer = new Timer(ONE_SECOND, e -> updateRemainingTime(timeLabel, startButton, stopButton));
        timer.setRepeats(true); // 设置为true，定时器一直运行
        timer.start();

        // 禁用开始按钮，启用停止按钮
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
    }

    /**
     * 如果有正在运行的计时器，先停止
     *
     * @param startButton
     * @param stopButton
     */
    private static void stopFocusTimer(JButton startButton, JButton stopButton) {
        if (timer != null && timer.isRunning()) {
            timer.stop();
        }

        // 启用开始按钮，禁用停止按钮
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
    }

    private static void createTrayIcon() {
        if (SystemTray.isSupported()) {

            SystemTray tray = SystemTray.getSystemTray();

            // 加载托盘图标（根据实际路径调整）
            Image image = Toolkit.getDefaultToolkit().getImage("pic/akx.png");

            // 创建弹出菜单
            JPopupMenu popup = new JPopupMenu();

            JMenuItem showItem = new JMenuItem("显示窗口");
            showItem.addActionListener(e -> {
                // 当点击"显示窗口"菜单项时，重新显示窗口
                trayIconClicked();
            });

            JMenuItem exitItem = new JMenuItem("退出");
            exitItem.addActionListener(e -> {
                // 在退出时移除托盘图标
                tray.remove(trayIcon);
                System.exit(0);
            });

            popup.add(exitItem);
            popup.add(showItem);

            // 创建托盘图标
            trayIcon = new TrayIcon(image, "专注助手");
            trayIcon.setImageAutoSize(true);

            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        trayIconClicked();
                    }
                }
                @Override
                public void mouseReleased(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        popup.setLocation(e.getX(), e.getY());
                        popup.setInvoker(popup);
                        popup.setVisible(true);
                    }
                }
            });
            trayIconCreated = true;
            try {  // 将托盘图标添加到系统托盘
                tray.add(trayIcon);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        }
    }

    private static void trayIconClicked() {
        // 当托盘图标被点击时，显示窗口
        if (frame != null) {
            frame.setVisible(true);
            frame.setExtendedState(JFrame.NORMAL);
            frame.toFront();
        }
    }

    private static void updateRemainingTime(JLabel timeLabel, JButton startButton, JButton stopButton) {
        remainingTime -= ONE_SECOND;
        if (remainingTime <= 0) {
            stopFocusTimer(startButton, stopButton);
            remainingTime = 0;
            showNotification("休息一下！", "您已完成专注时间。");
        }

        // 更新界面上的剩余时间显示
        updateUI(timeLabel);

        // 更新托盘图标的提示文本
        updateTrayIconToolTip(timeLabel.getText());
    }

    private static void updateUI(JLabel timeLabel) {
        long minutes = remainingTime / ONE_SECOND / 60;
        long seconds = (remainingTime / ONE_SECOND) % 60;
        timeLabel.setText("剩余时间: " + minutes + " 分 " + seconds + " 秒");
    }

    private static void updateTrayIconToolTip(String toolTip) {
        // 获取系统托盘
        SystemTray tray = SystemTray.getSystemTray();

        // 获取托盘图标
        TrayIcon trayIcon = tray.getTrayIcons()[0];

        // 在托盘图标上显示计时器剩余时间
        trayIcon.setToolTip(toolTip);
    }

    private static void showNotification(String title, String message) {
        // 在通知中显示消息
        // JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
        new Windows().init();
    }
}
